<template>
  <div class="id-front">
    <upload-card
      imgTitle="身份证人像面"
      v-on="$listeners"
      :defaultBgImg="bgImg"
      :accept="imageLimit"
      :imgUrl='imgUrl'
      v-bind="$attrs"
      :isClick="false"
      :disabled="uploadDisabled"
      :before-upload="idFrontUrlBeforeUpload"
      :http-request="idFrontToRequest"
      @getQrImg='getOrCodeImg'
    />
  </div>
</template>
<script>
import UploadCard from '@/moduleComponents/licence/common/uploadCard.vue'
import { fileUpload } from '@const/api.js'
export default {
  name: 'idFront',
  inheritAttrs: false,
  components: {
    UploadCard
  },
  props:{
    imgUrl:{
      default: '',
      type: String
    },
    disabled:{
      default: false,
      type: Boolean
    }
  },
  computed: {
    getImgUrl() {
      if(this.imgUrl) {
        return this.imgUrl
      }
      return this.bgImg
    }
  },
  watch: {
    disabled:{
      handler(nv,ov) {
       this.uploadDisabled = nv
      }
    }
  },
  data() {
    return {
      bgImg: require('./img/pc-qyrz-glyzl-sfzzm-bg.png'),
      imageLimit: '.png, .jpg, .jpeg',
      uploadDisabled: this.disabled
    }
  },
  methods: {
    getOrCodeImg(imgUrl) {
      this.$emit('uploadCb',{
        payload: imgUrl
      })
    },
    // 身份证正面上传
    idFrontUrlBeforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 10
      const isAcceptype = this.imageLimit.split(', ').filter(item => file.name.includes(item))
      if (!isAcceptype.length) {
        this.uploadLoading = false
        this.$message.error('文件后缀名必须为png，jpg，jpeg，文件大小不得大于10M')
        return false
      }
      if (!isLt2M) {
        this.$message.error('文件后缀名必须为png，jpg，jpeg，文件大小不得大于10M')
        return false
      }
    },
    idFrontToRequest(fileData) {
      this.uploadDisabled = true
      let fd = new FormData()
      fd.append('file', fileData.file)
      this.$axios({
        method: 'post',
        url: fileUpload,
        headers: { 'Content-Type': 'multipart/form-data' },
        data: fd
      })
      .then(({ data }) => {
        if (!Object.is(data.code, '0')) return
        this.$emit('uploadCb',data)
      }).catch(err => {
        this.$message.success('上传失败')
        this.$emit('uploadCb')
      })
      .finally(() => {
        this.uploadDisabled = false
      })
    }
  }
}
</script>
<style lang="less">
.id-front {
  
}
</style>
